<template>
  <div class="custom-tree-container">
    <!-- <el-tree :data="store.$state.ruleLeft" :props="defaultProps" node-key="id" default-expand-all
      :expand-on-click-node="false">
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span>{{ node.label }}</span>
          <span>
            <div style="display: flex;">
              <div> 管理员 </div>
              <div style="margin-left: 8px"> 操作 </div>
            </div>
          </span>
        </span>
      </template>
</el-tree> -->
    <el-tree style="max-width: 100%" :data="store.$state.ruleLeft" :props="defaultProps" :default-expand-all="true"
      :expand-on-click-node="false">
      <template #default="{ node, data }">
        <div class="custom-tree-node" style='width:100%;display:flex;justify-content:space-between;align-items:center'>
          <span>{{ node.label }}</span>
          <div style="width:170px;display:flex;justify-content:space-between;align-items:center">
            <p style="margin:10px">{{ data.managerName }}</p>
            <el-dropdown>
              <div style='margin:10px;display:flex;align-items:center;'>
                <span>操作</span>
                <img src="../../public/下箭头.png" alt="" style="width:14px;height:14px;margin-left:10px;">
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="addDepartments(data)">添加子部门</el-dropdown-item>
                  <el-dropdown-item @click="editDepartments(data)">编辑部门</el-dropdown-item>
                  <el-dropdown-item @click="deleteDepartments(data.id)">删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </template>
    </el-tree>
    <!-- 对话框  添加/编辑 -->
    <el-dialog v-model="show" :title="title" :width="title == '新增角色' || title == '编辑角色' ? '500px' : '845px'"
      align-center :destroy-on-close="true">
      <el-form ref="ruleFormRef" style="max-width:100%" :model="ruleForm" :rules="rules" label-width="auto"
        class="demo-ruleForm" :size="formSize" status-icon>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="2-10个字符" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="ruleForm.code" placeholder="2-10个字符" />
        </el-form-item>
        <el-form-item label="部门负责人" prop="managerId">
          <el-select v-model="ruleForm.managerId" placeholder="请选择负责人">
            <el-option v-for="item in principalList" :key="item.id" :label="item.username" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input v-model="ruleForm.introduce" :rows="4" type="textarea" placeholder="1-100个字符" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            确定
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script setup>
import { useStore } from '@/stores/counter'
import { ref, onMounted } from "vue"
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDepartmentList, getPrincipalList, addDepartment, getDepartmentDetail, editDepartment, deleteDepartment } from "../api/getDepartmentData"
const store = useStore()
store.render2()
//TODO:数据
let loading = ref(true)
let departmentList = ref([])
let principalList = ref([])
let defaultProps = {
  children: 'children',
  label: 'name',
}
let title = ref("添加部门")
let show = ref(false)
const formSize = ref('default')
const ruleFormRef = ref()
const ruleForm = ref({
  name: '',
  code: '',
  managerId: '',
  introduce: ''
})
const rules = ref({
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 2, max: 10, message: '请输入2-10个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入部门编码', trigger: 'blur' },
    { min: 2, max: 10, message: '请输入2-10个字符', trigger: 'blur' }
  ],
  managerId: [
    { required: true, message: '请选择部门负责人', trigger: 'blur' }
  ],
  introduce: [
    { required: true, message: '请输入部门介绍', trigger: 'blur' },
    { min: 1, max: 100, message: '请输入1-100个字符', trigger: 'blur' }
  ]
})
let editObject = ref({})
//TODO:方法
//获取部门列表数据
const getDepartmentListData = async () => {
  let res = await getDepartmentList()
  loading.value = false
  store.render2()
}
//获取部门负责人数据
const getPrincipalListData = async () => {
  const res = await getPrincipalList()
  principalList.value = res.data.data
}
//添加子部门
const addDepartments = (data) => {
  editObject.value = data
  title.value = "添加部门"
  show.value = true
  ruleForm.value = {
    name: '',
    code: '',
    managerId: '',
    introduce: ''
  }
}
//编辑部门
const editDepartments = async (data) => {
  const res = await getDepartmentDetail(data.id)
  editObject.value = data
  ruleForm.value = res.data.data
  title.value = "编辑部门"
  show.value = true
}
//删除部门
const deleteDepartments = (id) => {
  ElMessageBox.confirm(
    '确认要删除该部门?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: true,
    }
  )
    .then(async () => {
      const res = await deleteDepartment(id)
      if (res.data.success) {
        ElMessage({
          message: res.data.message,
          type: 'success',
        })
        getDepartmentListData()
      } else {
        ElMessage({
          message: res.data.message,
          type: 'error',
        })
      }
    })
    .catch((err) => {
      console.log(err);
    })
}
//表单验证成功
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (title.value == "添加部门") {
        ruleForm.value.pid = String(editObject.value.pid)
        const res = await addDepartment(ruleForm.value)
        console.log(res);
        if (res.data.success) {
          ElMessage({
            message: res.data.message,
            type: 'success',
          })
          getDepartmentListData()
          show.value = false
        } else {
          ElMessage({
            message: res.message,
            type: 'error',
          })
        }
      } else {
        const res = await editDepartment(ruleForm.value)
        if (res.data.success) {
          ElMessage({
            message: res.data.message,
            type: 'success',
          })
          getDepartmentListData()
          show.value = false
        } else {
          ElMessage({
            message: res.data.message,
            type: 'error',
          })
        }
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
//表单验证失败
const resetForm = (formEl) => {
  if (!formEl) return
  show.value = false
  formEl.resetFields()
}
//TODO:组件执行的生命周期
onMounted(() => {
  getDepartmentListData()
  getPrincipalListData()
})
</script>

<style scoped>
@import "@/assets/organize.css";
</style>
